<?php
/**
 * Created by JetBrains PhpStorm.
 * User: akrug
 * Date: 31.05.12
 * Time: 09:46
 * To change this template use File | Settings | File Templates.
 */
abstract class UcsMvc_AbstractController extends Zend_Controller_Action
{
    /**
     * @var Zend_Translate
     */
    protected $_translator = null;

    /**
     * contains language parameter
     *
     * @var string
     */
    protected $_currentLanguage = 'de';

    /**
     * @var string
     */
    protected $_message = null;

    /**
     * @var Zend_Auth
     */
    protected $_identity = null;

    /**
     * @var Model_UserAcl
     */
    protected $_acl = null;

    public function __construct(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response, array $invokeArgs = array()){
        parent::__construct($request, $response, $invokeArgs);

        $this->_currentLanguage = Zend_Registry::get('Zend_Locale')->getLanguage();
        $this->_translator      = Zend_Registry::get('Zend_Translate');

        //bezieht angemeldeten Benutzer
        $this->_identity = $this->readIdentity();

        //ACL
        $this->_acl = new Model_UserAcl();

        //meldungen die mit forwarding gesendet werden
        if($this->_hasParam('message')){
            $this->_message = $this->_getParam('message');
        }
    }

    public function indexAction(){

        $rows = $this->_mainTable->getTableList();

        if(empty($rows)){
            $this->_message = $this->_translator->translate('Dieser Bereich enthält keine Einträge.', $this->_currentLanguage);
        }

        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($rows));

        $this->view->rows      = $rows;
        $this->view->paginator = $paginator;
        $this->view->message   = $this->_message;
    }

    public function addAction(){
        $form = $this->createObject('Form');
        $form->addSubForm(new Backend_Form_Confirm(), 'confirm');

        if($this->_hasParam('submit')){
            if($form->isValid($this->_getAllParams())){
                $this->_mainTable->addRow($this->_getAllParams());
                $this->_message = $this->_translator->translate('Der Vorgang wurde erfolgreich durchgeführt.');
                $this->_forward('index', null, null, array('message' => $this->_message));
            }
        }elseif($this->_hasParam('cancle')){
            $this->_message = $this->_translator->translate('Der Vorgang wurde abgebrochen.', $this->_currentLanguage);
            $this->_forward('index', null, null, array('message' => $this->_message));
        }

        $this->view->message = $this->_message;
        $this->view->form    = $form;
    }

    public function editAction(){

        //formularklassenname wird validiert
        $form = $this->createObject('form');
        $form->addSubForm(new Backend_Form_Confirm(), 'confirm');

        if($this->getRequest()->isGet()){
            //zeige sicherheitsabfrage
            //uebergebe seitenzahl und suchparameter
            if(!$this->validParams()){
                $this->_message = $this->_translator->translate('Die verwendete ID ist ungültig.', $this->_currentLanguage);
                //button submit wird entfernt
                $form->removeElement('submit');
            }else{
                //fuege dem formular die unternehmensdaten hinzu
                $form->populate($this->_mainTable->getRow($this->_getParam('id')));
            }
        }else{
            //wenn cancle button gedrueckt
            if($this->_hasParam('cancle')){
                $this->_message = $this->_translator->translate('Der Vorgang wurde abgebrochen.', $this->_currentLanguage);
                $this->_forward('index', null, null, array('message' => $this->_message));
            }

            if($this->_hasParam('submit')){
                if($form->isValid($this->_getAllParams())){
                    $this->_mainTable->editRow($this->_getAllParams());
                    $this->_message = $this->_translator->translate('Der Vorgang wurde erfolgreich durchgeführt.', $this->_currentLanguage);

                    $this->_forward('index', null, null, array('message' => $this->_message));
                }
            }
        }

        $this->view->message = $this->_message;
        $this->view->form    = $form;
    }

    public function deleteAction(){
        $form = new Backend_Form_Confirm();

        if($this->getRequest()->isGet()){
            //zeige sicherheitsabfrage
            //uebergebe seitenzahl und suchparameter
            if(!$this->validParams()){
                $this->_message = $this->_translator->translate('Die verwendete ID ist ungültig.', $this->_currentLanguage);
                //button submit wird entfernt
                $form->removeElement('submit');
            }
        }else{
            //wenn cancle button gedrueckt
            if($this->_hasParam('cancle')){
                $this->_message = $this->_translator->translate('Der Vorgang wurde abgebrochen.', $this->_currentLanguage);
            }

            if($this->_hasParam('submit')){
                $this->_mainTable->deleteRow($this->_getParam('id'));
                $this->_message = $this->_translator->translate('Der Vorgang wurde erfolgreich durchgeführt.', $this->_currentLanguage);
            }

            //wird nach submit oder canle vorgang durchgefuehrt
            $this->_forward('index', null, null, array('message' => $this->_message));
        }

        $this->view->message = $this->_message;
        $this->view->form    = $form;
    }

    /**
     *  hier wird eine zeile ge- oder entsperrt
     */
    public function lockAction(){
        $form = new Backend_Form_Confirm();

        if($this->getRequest()->isGet()){
            //zeige sicherheitsabfrage
            //uebergebe seitenzahl und suchparameter
            if(!$this->validParams()){
                $this->_message = $this->_translator->translate('Die verwendete ID ist ungültig.', $this->_currentLanguage);
                //button submit wird entfernt
                $form->removeElement('submit');
            }
        }else{
            //wenn cancle button gedrueckt
            if($this->_hasParam('cancle')){
                $this->_message = $this->_translator->translate('Der Vorgang wurde erfolgreich durchgeführt.', $this->_currentLanguage);
            }

            if($this->_hasParam('submit')){
                $this->_mainTable->lock($this->_getParam('id'));
                $this->_message = $this->_translator->translate('Der Vorgang wurde erfolgreich durchgeführt.', $this->_currentLanguage);
            }

            //wird nach submit oder canle vorgang durchgefuehrt
            $this->_forward('index', null, null, array('message' => $this->_message));
        }

        $this->view->message = $this->_message;
        $this->view->form    = $form;
    }

    /**
     * @return bool
     */
    protected function validParams(){
        $valid  = true;
        $params = $this->_getAllParams();

        //check user id
        if(!isset($params['id'])){
            $valid = false;
        }

        //check language

        //check page
        if(!isset($params['page'])){
            $this->_setParam('page', '1');
        }

        //check searchparam
        if(!isset($params['search'])){
            $this->_setParam('search', '');
        }


        return $valid;
    }

    /**
     * @param $type
     * @return null
     * @throws Exception
     */
    private function createObject($type){
        $form = null;
        //formularklassenname wird validiert
        if(is_string($this->_controllerName) && is_string($this->_formSubFolder)){
            $className = ucfirst(strtolower($this->_request->getModuleName()))
                        .'_'
                        .ucfirst(strtolower($type))
                        .'_';
            if($this->_formSubFolder != ''){
                $className .= ucfirst(strtolower($this->_formSubFolder)).'_';
            }
            $className .= ucfirst(strtolower($this->_controllerName));

            $form = new $className();
        }else{
            throw new Exception($this->_translator->translate($this->_controllerName.'MajorError', $this->_currentLanguage));
        }

        if(!$form){
            throw new Exception($this->_translator->translate($this->_controllerName.'MajorError', $this->_currentLanguage));
        }

        return $form;
    }

    /*
     * liest die Benutzerdaten des angemeledeten Benutzers aus
     */
    protected function readIdentity(){
        if(Zend_Auth::getInstance()->hasIdentity()){
            return Zend_Auth::getInstance()->getIdentity();
        }else{
            return false;
        }
    }

    protected function accesAllowed($privilege){
        $module     = strtolower($this->_request->getModuleName());
        $controller = strtolower($this->_request->getControllerName());
        $resource   = strtolower($module.':'.$controller);

        if($this->_acl->isAllowed($this->_identity->role, $resource, $privilege)){
            return true;
        }else{
            return false;
        }
    }
}